package com.eage.security.mobilevalidate;


import com.eage.security.exception.MobileCodeNotFoundException;
import com.eage.security.properties.CompanyProperties;
import com.eage.security.mobilevalidate.MobileRedisProvider;
import com.eage.security.utils.ShiroPublicUtil;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class MobileRedisProviderImpl implements MobileRedisProvider {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CompanyProperties companyProperties;

    @Override
    public void save(String mobile ,String code) {
        Preconditions.checkArgument(ShiroPublicUtil.isNotEmpty(code)&&ShiroPublicUtil.isNotEmpty(mobile),"手机号或者验证码不能传为空" );
        String key = this.buildRedisKey(mobile);
        //设置手机号和验证码绑定,并让验证码jwt,可以看作进行过期时间jwt的验证
        redisTemplate.opsForValue().set(key, code, companyProperties.getMobileCode().getTime(), TimeUnit.MINUTES);
        log.warn("给手机号[ {} ]发送一条短信 验证码为: [ {} ]", mobile, code);
    }

    @Override
    public void validate(String mobile, String code) {
        Preconditions.checkArgument(ShiroPublicUtil.isNotEmpty(code)&&ShiroPublicUtil.isNotEmpty(mobile),"手机号或者验证码不能传为空" );
        //redis中存储的手机号key
        String key = this.buildRedisKey(mobile);
        //redis中取的已经有的code,需要后续解析
        String redisCode = redisTemplate.opsForValue().get(key);
        if (ShiroPublicUtil.isEmpty(redisCode)||!redisCode.equals(code)) {
            log.error("手机号验证码登入校验失败 mobile=[ {} ]", mobile);
            throw new MobileCodeNotFoundException("验证错误");
        }
    }

    private String buildRedisKey(String mobile){
        return companyProperties.getMobileCode().getName().concat(":").concat(mobile);
    }

}
